//
//  SetSilentTimeViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/22.
//  Copyright (c) 2015年 张旭. All rights reserved.
//

#import "SetSilentTimeViewController.h"
#import "AppDelegate.h"
#import "SelectRateViewController.h"

#import "SyncManager.h"
#import "DataManager.h"
#import "LeoMsg.h"


@interface SetSilentTimeViewController ()

@property (nonatomic,retain) SyncManager *syncManager;
@property (nonatomic,retain) DataManager *dataManager;

@end

@implementation SetSilentTimeViewController
@synthesize navLeftButton;
@synthesize navRightButton;
@synthesize startDatePicker;
@synthesize startDatePickerWidth;
@synthesize endDatePicker;
@synthesize endDatePickerWidth;
@synthesize rateLabel;
@synthesize rateView;
@synthesize rateString;
@synthesize startDateString;
@synthesize endDateString;
@synthesize silentIDString;

-(void)dealloc
{
    rateString=NULL;
    startDateString=NULL;
    endDateString=NULL;
    silentIDString=NULL;
    self.syncManager=NULL;
    self.dataManager=NULL;
}
-(void)viewWillAppear:(BOOL)animated
{
    if (rateString!=NULL){rateLabel.text=rateString;}
    if (startDateString!=NULL)
    {
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"]; //大写的 H为24小时制，小写h为12小时制

        NSDate *startDate= [dateFormatter dateFromString:startDateString];
        NSDate *endDate= [dateFormatter dateFromString:endDateString];

        startDatePicker.date=startDate;
        endDatePicker.date=endDate;

    }

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"添加免打扰时段";
    self.navigationItem.rightBarButtonItem=navRightButton;
    
    [self initNavButton];
    [self initDataProxy];
    [self initActions];
    startDatePickerWidth.constant = CGRectGetWidth(self.view.bounds)/2;
    endDatePickerWidth.constant = CGRectGetWidth(self.view.bounds)/2;
    // Do any additional setup after loading the view from its nib.
    
    startDatePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"NL"];
    endDatePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"NL"];
}
-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
}
-(void)initActions{
    
    UITapGestureRecognizer *tapReconizerToSelectRate = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setRateAction)];
    [self.rateView addGestureRecognizer:tapReconizerToSelectRate];
    
}

-(void)setTitleAction{
    
}

-(void)setRateAction{
    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    SelectRateViewController *selectRate=[[SelectRateViewController alloc]init];
    [selectRate setMotherWindow:alertView];
    [selectRate setMotherLabel:rateLabel];
    alertView.rootViewController=selectRate;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];
}

- (void)initNavButton {
    [navLeftButton setTarget:self];
    [navLeftButton setAction:@selector(back)];
    
    [navRightButton setTarget:self];
    [navRightButton setAction:@selector(saveAction)];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
    //[self dismissViewControllerAnimated:YES completion:nil];
}


-(void)saveAction{
  
    navRightButton.enabled=NO;
    NSTimeInterval f=[startDatePicker.date timeIntervalSinceDate:endDatePicker.date];
    if ((f>=-1)&&(f<=1))
    {
        [LeoMsg showMsg:@"开始时间不能和结束时间相同"];
        [navRightButton setAction:@selector(saveAction)];
        navRightButton.enabled=YES;
        return;
    }

    if (f>0)
    {
        [LeoMsg showMsg:@"开始时间不能晚于结束时间"];
        [navRightButton setAction:@selector(saveAction)];
        navRightButton.enabled=YES;
        return;
    }
    
    
    
    
    Silent *silent=[[Silent alloc] init];
    silent.title=@"keep silent";
    silent.desc=@"at class,please don not speak";
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"]; //大写的 H为24小时制，小写h为12小时制
    NSString* startDateStr = [dateFormatter stringFromDate:startDatePicker.date];
    NSString* endDateStr = [dateFormatter stringFromDate:endDatePicker.date];

    silent.startTime=startDateStr;
    silent.endTime=endDateStr;
    silent.active=1;
    silent.cycle=[self changeSilentCycle:rateLabel.text];
    
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;

    if (silentIDString!=NULL)
    {
        silent.slient_id=silentIDString;
        BOOL isExist=[self.dataManager IsSameSilent:watchId silent:silent isNew:NO];
        if(isExist)
        {
            [LeoMsg showToastMsg:@"免打扰时段已存在" parentView:self.navigationController.view showPosition:TOAST_SHOW_MID hideAfterDelay:1];
            navRightButton.enabled=YES;
            return;
        }

        Silent *originalSilent=[self.dataManager getSilent:silentIDString];
        silent.active=originalSilent.active;
        [self.syncManager setSilentPeriod:watchId silent:silent completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            
            if (result==SUCESS)
            {
                [self.navigationController popViewControllerAnimated:YES];
                
            }
            else
            {
                [Tooler showHttpMsg:result description:description msg:@"免打扰时段修改失败"];
            }
            
        }];
        navRightButton.enabled=YES;
        return;
    }

    BOOL isExist=[self.dataManager IsSameSilent:watchId silent:silent isNew:YES];
    if(isExist)
    {
        [LeoMsg showToastMsg:@"免打扰时段已存在" parentView:self.navigationController.view showPosition:TOAST_SHOW_MID hideAfterDelay:1];
        navRightButton.enabled=YES;
        return;
    }
    [self.syncManager addSilentPeriod:watchId silent:silent completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
    
    if (result==SUCESS)
    {
        [self.navigationController popViewControllerAnimated:YES];

    }
    else
    {
        [Tooler showHttpMsg:result description:description msg:@"免打扰时段添加失败"];
    }
    navRightButton.enabled=YES;
    }
    ]; 
}

-(NSString *)changeSilentCycle:(NSString *)cycle
{
    NSString *newCycle=@"";
    
    if ([cycle isEqualToString:@"每天"]){return @"1,2,3,4,5,6,7";}
    
    for (int i=0;i<cycle.length;i=i+3)
    {
            NSRange range = NSMakeRange(i, 2);
            NSString *subString = [cycle substringWithRange:range];
            
            if ([subString isEqual:@"周一"]){newCycle=[newCycle stringByAppendingString:@"1,"];}
            if ([subString isEqual:@"周二"]){newCycle=[newCycle stringByAppendingString:@"2,"];}
            if ([subString isEqual:@"周三"]){newCycle=[newCycle stringByAppendingString:@"3,"];}
            if ([subString isEqual:@"周四"]){newCycle=[newCycle stringByAppendingString:@"4,"];}
            if ([subString isEqual:@"周五"]){newCycle=[newCycle stringByAppendingString:@"5,"];}
            if ([subString isEqual:@"周六"]){newCycle=[newCycle stringByAppendingString:@"6,"];}
            if ([subString isEqual:@"周日"]){newCycle=[newCycle stringByAppendingString:@"7,"];}
        
    }
    if ([newCycle isEqualToString:@""])
    {
        return newCycle;
    }
    else
    {
        NSRange range = NSMakeRange(0, newCycle.length-1);
        newCycle = [newCycle substringWithRange:range];
        return newCycle;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
